<?php
/**
 * 计算用户
 * 判断用户余额正确与否
 */header("Content-Type:text/html;charset=UTF-8");
$link = mysql_connect('203.171.231.25:3306', 'wgz', 'ad369/*-');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
if (!mysql_select_db('kkyoo_kbao', $link)) {
	die('Could not select database: '.mysql_error());
}

$sqlU = "SELECT user_id from bus_deal2 group by user_id ;";
$reU = mysql_query($sqlU);

//$idArray = array(51111,53333,55555, 100007, 108898, 434477, 462274,464488 ,469136, 469480, 470292, 470818, 475840, 477851);

for ($i=1; $U = mysql_fetch_assoc($reU); $i++){

	$user_id = 	$U['user_id'];
$update =  false; //false; //true; 



$query = "SELECT * from bus_deal2 where user_id = {$user_id} order by time ;";
			
$result = mysql_query($query, $link);
if (!$result) {
    die('DB Error, could not query the database： '.mysql_error());
}

$sumMoney = 0;
while ( $row = mysql_fetch_assoc($result) ){
	//var_dump($row);
	if ( !empty($row['kbi_num']) ) {
	switch ( $row['flag'] ){
		case 1:
			$sumMoney += $row['kbi_num']; 
//			echo "存入：{$row['kbi_num']}";
			break;
		case 2:
			$sumMoney -= $row['kbi_num'];
//			echo "取出：{$row['kbi_num']}";
			break;
		case 3:
			$sumMoney -= $row['kbi_num']; 
//			echo "买入：{$row['kbi_num']}";
			break;
		case 4:
			$sumMoney += $row['kbi_num']; 
//			echo "卖出：{$row['kbi_num']}";
			break;
		case 5:
//			echo "交税：{$row['kbi_num']}";
			$sumMoney -= $row['kbi_num']; 
			break;
	}
//		echo "  -->  余额: {$sumMoney}<br />";	
	$sql = "UPDATE `bus_deal2` SET `kbi_left` = '{$sumMoney}' WHERE `bus_deal2`.`pay_id` = {$row['pay_id']} LIMIT 1 ;";
	if ($update)
		mysql_query($sql);
	//echo $sql.'<br />';
	} //END if
}

$sql2 = "UPDATE `bus_user` SET `kbi_left` = '{$sumMoney}' WHERE `bus_user`.`user_id` = {$user_id} LIMIT 1 ;";
if ($update) mysql_query($sql2);
//echo "<hr />OVER {$user_id} !";


$sql3 = "SELECT * from bus_user where user_id = {$user_id};";
$re3 = mysql_query($sql3);
$row3 = mysql_fetch_assoc($re3);

if ($sumMoney < $row3['kbi_left'])
	echo "<{$i}> {$user_id}  ->   <span style=\"color:red;\">{$sumMoney}</span> / {$row3['kbi_left']}<br />\t\n";
else 
	echo "<{$i}> {$user_id}  ->   {$sumMoney} / {$row3['kbi_left']}<br />\t\n";
}// ENF foreach

?>